package com.haifeng.jupiter.common.core.exception;


import com.haifeng.jupiter.common.core.base.Rest;
import com.haifeng.jupiter.common.core.constant.StatusCode;
import com.haifeng.jupiter.common.core.util.MessageUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <p>
 * 全局异常捕获
 * </p>
 *
 * @Author: Haifeng
 * @Date: 2020-08-09
 */
@Slf4j
@AllArgsConstructor
@RestControllerAdvice
public class GlobalExceptionAdvice {

    private final MessageUtils messageUtils;

    /**
     * 处理参数校验异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(ValidException.class)
    public Rest validException(ValidException exception) {
        Rest restfulMessage = Rest.error(exception.getCode(), exception.getMessage());
        return restfulMessage;
    }

    /**
     * 处理业务异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public Rest businessException(BusinessException exception) {
        Rest restfulMessage = Rest.error(exception.getCode(), exception.getMessage());
        log.warn("【项目发生业务异常】：{}", restfulMessage);
        return restfulMessage;
    }

    /**
     * 处理系统异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Rest globalException(Exception exception) {
        log.error("【项目发生异常】：{}", exception);
        return Rest.error(StatusCode.HTTP_INTERNAL_ERROR, messageUtils.get(StatusCode.HTTP_INTERNAL_ERROR));
    }
}
